package cz.muni.fi.pa036.kiss.daoimpl;

import cz.muni.fi.pa036.kiss.Entity.Kolej;
import cz.muni.fi.pa036.kiss.dao.KolejDAO;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author peter
 */
public class KolejDAOImpl implements KolejDAO{

    @PersistenceContext
    private EntityManager em;
    
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }
    
    @Override
    public void create(Kolej kolej) {
        if (kolej == null) {
            throw new IllegalArgumentException("kolej is null");
        }
        if (kolej.getId() != null) {
            throw new IllegalArgumentException("kolej.id is not null");
        }

        em.persist(kolej);
    }

    @Override
    public Kolej get(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("null id");
        }
        Kolej kolej = em.find(Kolej.class, id);
        return kolej;
    }

    @Override
    public void update(Kolej kolej) {
        if (kolej == null) {
            throw new IllegalArgumentException("kolej is null");
        }
        if (kolej.getId() == null) {
            throw new IllegalArgumentException("kolej.id is null");
        }
        
        em.merge(kolej);
    }

    @Override
    public void remove(Kolej kolej) {
        if (kolej == null) {
            throw new IllegalArgumentException("kolej is null");
        }
        if (kolej.getId() == null) {
            throw new IllegalArgumentException("kolej.id is null");
        }
        Kolej c = em.find(Kolej.class, kolej.getId());
        em.remove(c);
    }

    @Override
    public List<Kolej> findAll() {
        Query query = em.createQuery("SELECT c FROM Kolej c");
        List<Kolej> results = query.getResultList();

        return results;
    }

    @Override
    public List<Kolej> findByName(String nazev) {
        boolean nazevNull = (nazev == null);
        if (nazevNull) {
            throw new IllegalArgumentException("null nazev");
        }

        Query query;
        query = em.createQuery("SELECT c FROM Kolej c WHERE c.nazev like :nazev");
        query.setParameter("nazev", nazev);

        List<Kolej> results = query.getResultList();
        return results;
    }
    
}
